﻿using System;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using SpCop.Core.Model;
using SpCop.Model;

namespace SpCop.Localization
{
    public class PageLayoutsAndMasterPageResourceStringsAreValid : ModuleRuleBase
    {
        public PageLayoutsAndMasterPageResourceStringsAreValid()
            : base(a => a == "_catalogs/masterpage")
        {
            
        }
        protected override void VisitModule(Package package, Feature feature, Element item)
        {
           
                foreach (var file in GetFileElements(item.Xml))
                {
                    var urlValue = file.Attribute("Url").Value;
                    var path = Path.Combine(Path.Combine(Package.Path, feature.Folder), urlValue);

                    if (!File.Exists(path))
                    {

                    }
                    else
                    {
                        var ext = Path.GetExtension(path);

                        switch (ext)
                        {
                            case ".aspx":
                            case ".master":
                                var parsed = GetParsedContentFile(path);
                                foreach (var contentPart in parsed.Parts.Where(a => a.Type == MixedContentTypes.ResourceString))
                                {
                                    var s = contentPart.Match.ToString();
                                    if (!s.StartsWith("<%$Resour") && !s.StartsWith("<% $Resour"))
                                        continue;

                                    if(!ResourceStringExists(package, s))
                                        AddProblem("Found resource in page : {0}", s);
                                }
                                break;
                           
                        }
                    }
                }
            }

        private static bool ResourceStringExists(Package package, string s)
        {
            // todo : Check if resource is included.
            return true;

        }

       
    }
    
}